package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.Admin;
import it.polimi.swimv2.exception.ModifyException;
import it.polimi.swimv2.exception.UserDataError;
import it.polimi.swimv2.exception.UserDataException;
import it.polimi.swimv2.remote.AdminManagerRemote;
import it.polimi.swimv2.util.UserDataValidator;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ModifyAdminKeyManager
 */
@Stateless
public class AdminManager implements AdminManagerRemote {
	@PersistenceContext(unitName = "swimv2")
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public AdminManager() {

	}

	@Override
	public void modifyPassword(String username, String curPassword,
			String newPassword) throws UserDataException, ModifyException {
		Admin admin = null;
		if (username != null && curPassword != null) {
			admin = em.find(Admin.class, username);
		}
		if(admin==null||!admin.checkPassword(curPassword)){
			throw new ModifyException();
		}
		if(!UserDataValidator.passwordIsValid(newPassword)){
			throw new UserDataException(UserDataError.PWDERR);
		}
		admin.setPassword(newPassword);
		em.flush();
	}

}
